package com.activity;

import maps.test.R;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemSelectedListener;

import com.PrayTime.PrayTimeLayout;
import com.commun.AjouterMosque;
import com.commun.Param;
import com.commun.Utils;
import com.data.DataBaseQuery;
import com.geo.GeoTools;
import com.geo.MyMapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MyLocationOverlay;
import com.service.LocalServiceTimer;
import com.service.SilentService;
import com.service.AlarmServiceInterface.Stub;
import com.service.LocalServiceTimer.AlarmServiceInterfaceImp;

public class MyMapActivity extends MapActivity {
	private MyMapView myMapView;
	private MapController mapController;
	public final static Boolean DEVELOPER_MODE = true;
	private Boolean MapIntitialised = false;
	private MyLocationOverlay locationOverlay;
	private TabHost monTabHost;
	public static Location myLocation;
	public static GeoPoint myGeoPoint;
	public static Double mLatitude;
	public static Double mLongitude;
	public static LocalServiceTimer monServiceTimer = new LocalServiceTimer();
	public static Context mContext;
	private SharedPreferences app_preferences;

	public static Context getmContext() {
		return mContext;
	}

	public static void setmContext(Context mContext) {
		MyMapActivity.mContext = mContext;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		if (DEVELOPER_MODE) {
			StrictMode.enableDefaults();
		}
		mContext = this;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		IndependenteInitialise();
		InitialisationLocation();
		IntitialisationAnglet();
		IntialisationButtons();
		InitialisationServices();
		InitialisationMarqueurs();
	}

	private void IndependenteInitialise() {
		app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

	}

	private void InitialisationMarqueurs() {

		myMapView = Utils.MapMarqueurSetup(myMapView, this);

	}

	public TabHost getMonTabHost() {
		return monTabHost;
	}

	public void setMonTabHost(TabHost monTabHost) {
		this.monTabHost = monTabHost;
	}

	public void IntitialisationAnglet() {

		monTabHost = Utils.setupTabHost(
				(TabHost) findViewById(R.id.TabHostMenu), this);
	}

	private void InitialisationServices() {
		InitialisationSettingTabTimerNotification(this);
		InitialisationSettingTabSilentMode(this);

	}

	private void InitialisationLocation() {

		myMapView = (MyMapView) findViewById(R.id.mapView);
		mapController = myMapView.getController();
		mapController.setZoom(Param.ZOOM_LEVEL);
		myMapView.getZoomButtonsController();
		myMapView.setSatellite(true);

		locationOverlay = new MyLocationOverlay(MyMapActivity.this, myMapView);
		myMapView.getOverlays().add(locationOverlay);
		if (DEVELOPER_MODE) {
			mLatitude = 48.855279;// 36.859502;//
			mLongitude = 2.287939;// 10.168097;//
			myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
			myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
			mapController.animateTo(myGeoPoint);

		} else {
			myLocation = Utils.getCurrentLocation(MyMapActivity.this);

			mapController.animateTo(GeoTools.makeGeoPoint(myLocation
					.getLatitude(), myLocation.getLongitude()));
		}

		MapIntitialised = true;

	}

	ImageButton zoomInBotton;
	ImageButton zoomOutBotton;
	Button ajouterMosqueeSettingButtom;
	public static ImageButton ajouterMosqueeTagButton;
	public static Button terminerajouterMosqueeTagButton;
	Button autoSilentSettingsButton;

	private void IntialisationButtons() {
		zoomInBotton = (ImageButton) findViewById(R.id.ZoomInButton);
		zoomOutBotton = (ImageButton) findViewById(R.id.ZoomOutButton);
		ajouterMosqueeSettingButtom = (Button) findViewById(R.id.boutton_ajout_setting_mosquee);
		ajouterMosqueeTagButton = (ImageButton) findViewById(R.id.ajout_mosque_tag_buttom);
		terminerajouterMosqueeTagButton = (Button) findViewById(R.id.terminer_ajout_mosque_tag_buttom);
		autoSilentSettingsButton = (Button) findViewById(R.id.boutton_congif_mise_en_mode_selencieux_heure_priere);

		zoomInBotton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mapController.zoomIn();
			}
		});
		zoomOutBotton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mapController.zoomOut();

			}
		});

		ajouterMosqueeSettingButtom.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AjouterMosque.EditAjoutMosqueEnabling();
			}

		});
		ajouterMosqueeTagButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!AjouterMosque.isTagButtonActivate) {
					ajouterMosqueeTagButton
							.setBackgroundResource(R.drawable.light_grey_square);
					AjouterMosque.isTagButtonActivate = true;
				} else {
					ajouterMosqueeTagButton
							.setBackgroundResource(R.drawable.dk_grey_square);
					AjouterMosque.isTagButtonActivate = false;
				}

			}

		});
		terminerajouterMosqueeTagButton
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						AjouterMosque.TeminerAjoutMosque(MyMapActivity
								.getmContext());

					}

				});

		autoSilentSettingsButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				final ScrollView scroller = (ScrollView) findViewById(R.id.OngletSetting);
				final LinearLayout layout = (LinearLayout) findViewById(R.id.auto_silent_settings_layout);
				int size = 0;
				if (!isSilentSettingPrayTimeDisplayed) {
					size = maxHeight;
					isSilentSettingPrayTimeDisplayed = true;
					autoSilentSettingsButton
							.setCompoundDrawablesWithIntrinsicBounds(
									R.drawable.mute_blue, R.drawable.nop,
									R.drawable.btn_dropdown_up, R.drawable.nop);
				} else {
					isSilentSettingPrayTimeDisplayed = false;
					autoSilentSettingsButton
							.setCompoundDrawablesWithIntrinsicBounds(
									R.drawable.mute_blue, R.drawable.nop,
									R.drawable.btn_dropdown_down,
									R.drawable.nop);
				}
				layout.setLayoutParams(new LinearLayout.LayoutParams(
						android.view.ViewGroup.LayoutParams.FILL_PARENT, size));
				final Handler mHandler = new Handler();
				final Runnable mUpdateTimeTask = new Runnable() {
					public void run() {

						scroller.fullScroll(ScrollView.FOCUS_DOWN);
					}
				};
				mHandler.removeCallbacks(mUpdateTimeTask);
				mHandler.postDelayed(mUpdateTimeTask, 50);

			}
		});
	}

	private boolean isSilentSettingPrayTimeDisplayed = false;
	private final int maxHeight = 320;

	public int inc(int i) {
		return i++;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (MapIntitialised)
			locationOverlay.enableCompass();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (MapIntitialised)
			locationOverlay.disableCompass();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(maConnexionServiceNotification);
		unbindService(maConnexionServiceSilentMode);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	static AlarmServiceInterfaceImp _serviceInterface;
	public static ServiceConnection maConnexionServiceNotification = new ServiceConnection() {

		
		public void onServiceConnected(ComponentName name, IBinder service) {

			_serviceInterface = (AlarmServiceInterfaceImp) Stub
					.asInterface(service);

		}

		
		public void onServiceDisconnected(ComponentName name) {
			MyMapActivity.monServiceTimer = null;
			_serviceInterface = null;
		}
	};
	
	
	
	private SilentService monService;
	// L’objet ServiceConnection gère la connexion entre l’activité et le service.
	private ServiceConnection maConnexionServiceSilentMode = new ServiceConnection() {
	// Méthode appelée lorsque la connexion est établie. Récupère la référence
	// vers le service associé.
	public void onServiceConnected(ComponentName className, IBinder service) {
	monService = ((SilentService.MonServiceSilentBinder)service).getService();
	}
	// Méthode appelée lorsque la connexion est rompue.
	public void onServiceDisconnected(ComponentName className) {
	monService = null;
	}
	};

	
	

	public static Intent IntentServiceNotification(Context context) {

		return new Intent(context, LocalServiceTimer.class);
	}
	public static Intent IntentServiceSilentMode(Context context) {

		return new Intent(context, SilentService.class);
	}

	public void InitialisationSettingTabTimerNotification(final Context context) {

		// spinner rayon
		Spinner spinnerRayon = (Spinner) findViewById(R.id.RayonSetting);
		ArrayAdapter<CharSequence> adapterRayon = ArrayAdapter
				.createFromResource(this, R.array.rayon_nb_kilometre,
						android.R.layout.simple_spinner_dropdown_item);

		spinnerRayon.setAdapter(adapterRayon);
		spinnerRayon
				.setOnItemSelectedListener(new MyOnItemSelectedListenerRayonSetting());
		String rayonState = app_preferences.getString("rayon", "1");

		DataBaseQuery.rayon = Double.parseDouble(rayonState);
		if (rayonState.equals("5"))
			spinnerRayon.setSelection(0);
		else if (rayonState.equals("10"))
			spinnerRayon.setSelection(1);
		else if (rayonState.equals("100"))
			spinnerRayon.setSelection(2);
		else if (rayonState.equals("1000"))
			spinnerRayon.setSelection(3);

		// spinner Notification
		Spinner spinnerNotification = (Spinner) findViewById(R.id.NotificationSalatSetting);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.notification_setting_choises,
				android.R.layout.simple_spinner_dropdown_item);

		spinnerNotification.setAdapter(adapter);
		spinnerNotification
				.setOnItemSelectedListener(new MyOnItemSelectedListenerNotificationSetting());

		String notificationState = app_preferences.getString(
				"notificationState", "Désactivé");

		if (notificationState.equals("Désactivé")) {
			spinnerNotification.setSelection(0);
			Utils.notificationChoises = Utils.NotificationChoises.DESACTIVER;
		} else if (notificationState.equals("Activé")) {
			spinnerNotification.setSelection(1);
			Utils.notificationChoises = Utils.NotificationChoises.ACTIVER;
		} else if (notificationState.equals("Activé avec son")) {
			spinnerNotification.setSelection(2);
			Utils.notificationChoises = Utils.NotificationChoises.ACTIVER_SON;
		} else if (notificationState.equals("Activé avec vibration")) {
			spinnerNotification.setSelection(3);
			Utils.notificationChoises = Utils.NotificationChoises.ACTIVER_VIBRATION;
		} else if (notificationState.equals("Activé avec son/vibration")) {
			spinnerNotification.setSelection(4);
			Utils.notificationChoises = Utils.NotificationChoises.ACTIVER_SON_VIBRATION;
		}

		// spinnermethode de calcul
		Spinner spinnerMethCal = (Spinner) findViewById(R.id.MethCalculSalatSpinner);
		ArrayAdapter<CharSequence> adapterMethCal = ArrayAdapter
				.createFromResource(this, R.array.meth_cal_priere,
						android.R.layout.simple_spinner_dropdown_item);

		spinnerMethCal.setAdapter(adapterMethCal);
		spinnerMethCal
				.setOnItemSelectedListener(new MyOnItemSelectedListenerMethoCalcPriere());// !!!
		int methCalState = app_preferences.getInt("pray_time_cal_meth", 0);

		spinnerMethCal.setSelection(methCalState);

	}

	public void InitialisationSettingTabSilentMode(final Context context) {
		
		ToggleButton toggleButtonSilentMode = (ToggleButton) findViewById(R.id.auto_silent_activat_service);
		toggleButtonSilentMode.setOnClickListener(new MyOnClickListenerSilentMode());
		
		
		
	}
	private void startServiceNotification() {

		startService(IntentServiceNotification(this));

	}

	private void stopServiceNotification() {

		stopService(IntentServiceNotification(this));

	}

	private void bindServiceNotification() {

		bindService(IntentServiceNotification(this), maConnexionServiceNotification,
				Context.BIND_AUTO_CREATE);

	}

	private void releaseServiceNotification() {

		unbindService(maConnexionServiceNotification);

	}
	

	private void startServiceSilentMode() {

		startService(IntentServiceSilentMode(this));

	}

	private void stopServiceSilentMode() {

		stopService(IntentServiceSilentMode(this));

	}

	private void bindServiceSilentMode() {

		bindService(IntentServiceSilentMode(this), maConnexionServiceSilentMode,
				Context.BIND_AUTO_CREATE);

	}

	private void releaseServiceSilentMode() {

		unbindService(maConnexionServiceSilentMode);

	}

	private class MyOnClickListenerSilentMode implements OnClickListener{

		public void onClick(View v) {
			if (((ToggleButton) v).isChecked()){
				SharedPreferences.Editor editor = app_preferences.edit();
				
				String auto_silent_fajr_p = ((EditText) findViewById(R.id.auto_silent_fajr_arg1)).getText().toString();
				String auto_silent_fajr_d = ((EditText) findViewById(R.id.auto_silent_fajr_arg2)).getText().toString();
				String auto_silent_dhohr_p = ((EditText) findViewById(R.id.auto_silent_dhohr_arg1)).getText().toString();
				String auto_silent_dhohr_d = ((EditText) findViewById(R.id.auto_silent_dhohr_arg2)).getText().toString();
				String auto_silent_asr_p = ((EditText) findViewById(R.id.auto_silent_asr_arg1)).getText().toString();
				String auto_silent_asr_d = ((EditText) findViewById(R.id.auto_silent_asr_arg2)).getText().toString();
				String auto_silent_maghreb_p = ((EditText) findViewById(R.id.auto_silent_maghreb_arg1)).getText().toString();
				String auto_silent_maghreb_d = ((EditText) findViewById(R.id.auto_silent_maghreb_arg2)).getText().toString();
				String auto_silent_isha_p = ((EditText) findViewById(R.id.auto_silent_isha_arg1)).getText().toString();
				String auto_silent_isha_d = ((EditText) findViewById(R.id.auto_silent_isha_arg2)).getText().toString();
				
				if(!auto_silent_fajr_p.isEmpty() && !auto_silent_fajr_d.isEmpty()){
					editor.putInt("fajr_p", Integer.parseInt(auto_silent_fajr_p));
					editor.putInt("fajr_d", Integer.parseInt(auto_silent_fajr_d));
				}
				if(!auto_silent_dhohr_p.isEmpty() &&! auto_silent_dhohr_d.isEmpty()){
					editor.putInt("dhohr_p", Integer.parseInt(auto_silent_dhohr_p));
					editor.putInt("dhohr_d", Integer.parseInt(auto_silent_dhohr_d));
				}
				if(!auto_silent_asr_p.isEmpty() && !auto_silent_asr_d.isEmpty()){
					editor.putInt("asr_p", Integer.parseInt(auto_silent_asr_p));
					editor.putInt("asr_d", Integer.parseInt(auto_silent_asr_d));
				}
				if(!auto_silent_maghreb_p.isEmpty() && !auto_silent_maghreb_d.isEmpty()){
					editor.putInt("maghreb_p", Integer.parseInt(auto_silent_maghreb_p));
					editor.putInt("maghreb_d", Integer.parseInt(auto_silent_maghreb_d));
				}
				if(!auto_silent_isha_p.isEmpty() && !auto_silent_isha_d.isEmpty()){
					editor.putInt("isha_p", Integer.parseInt(auto_silent_isha_p));
					editor.putInt("isha_d", Integer.parseInt(auto_silent_isha_d));
				}
				editor.commit();
				bindServiceSilentMode();
				startServiceSilentMode();
				SilentService.isServiceStarted = true;
				 Toast.makeText(MyMapActivity.getmContext() , "Silent Service started... " ,
				 Toast.LENGTH_LONG).show();
				
			}
 		       
				
				else if (SilentService.isServiceStarted) {
					releaseServiceSilentMode();
					stopServiceSilentMode();
					SilentService.isServiceStarted = false;
					Toast.makeText(MyMapActivity.getmContext() , "Silent Service stoped. " ,
							 Toast.LENGTH_LONG).show();
							

				}
 			
		}
		
	}
	
	private class MyOnItemSelectedListenerNotificationSetting implements
			OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			SharedPreferences.Editor editor = app_preferences.edit();

			switch (pos) {
			case 0:
				Utils.notificationChoises = Utils.NotificationChoises.DESACTIVER;
				editor.putString("notificationState", "Désactivé");
				editor.commit();
				break;
			case 1:
				Utils.notificationChoises = Utils.NotificationChoises.ACTIVER;
				editor.putString("notificationState", "Activé");
				editor.commit();
				break;
			case 2:
				Utils.notificationChoises = Utils.NotificationChoises.ACTIVER_SON;
				editor.putString("notificationState", "Activé avec son");
				editor.commit();
				break;
			case 3:
				Utils.notificationChoises = Utils.NotificationChoises.ACTIVER_VIBRATION;
				editor.putString("notificationState", "Activé avec vibration");
				editor.commit();
				break;
			case 4:
				Utils.notificationChoises = Utils.NotificationChoises.ACTIVER_SON_VIBRATION;
				editor.putString("notificationState",
						"Activé avec son/vibration");
				editor.commit();
				break;
			}

			if (Utils.notificationChoises != Utils.NotificationChoises.DESACTIVER) {
				{
					if (LocalServiceTimer.isServiceStarted) {
						releaseServiceNotification();
						stopServiceNotification();
					}
					bindServiceNotification();
					startServiceNotification();
					LocalServiceTimer.isServiceStarted = true;
					Toast.makeText(MyMapActivity.getmContext() , "Timer Service started... " ,
							 Toast.LENGTH_LONG).show();
							
				}
			} else if (LocalServiceTimer.isServiceStarted) {
				releaseServiceNotification();
				stopServiceNotification();
				LocalServiceTimer.isServiceStarted = false;
				Toast.makeText(MyMapActivity.getmContext() , "Timer Service stoped... " ,
						 Toast.LENGTH_LONG).show();
						

			}
		}

		
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	public class MyOnItemSelectedListenerRayonSetting implements
			OnItemSelectedListener {

		
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			SharedPreferences.Editor editor = app_preferences.edit();

			switch (pos) {
			case 0:

				editor.putString("rayon", "5");
				editor.commit();
				break;
			case 1:

				editor.putString("rayon", "10");
				editor.commit();
				break;
			case 2:

				editor.putString("rayon", "100");
				editor.commit();
				break;
			case 3:

				editor.putString("rayon", "1000");
				editor.commit();
				break;

			}

			DataBaseQuery.rayonChanged = true;
		}

		
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	public class MyOnItemSelectedListenerMethoCalcPriere implements
			OnItemSelectedListener {

		
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			SharedPreferences.Editor editor = app_preferences.edit();

			editor.putInt("pray_time_cal_meth", pos);
			editor.commit();
			PrayTimeLayout.Renitialisation(MyMapActivity.mContext, pos);
		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}

	}

}

// Toast.makeText(MyMapActivity.getmContext() , "Time :" ,
// Toast.LENGTH_LONG).show();

/*
 * Set on full screan (au debut de onCreate)
 * this.requestWindowFeature(Window.FEATURE_NO_TITLE);
 * this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
 * WindowManager.LayoutParams.FLAG_FULLSCREEN );
 * super.onCreate(savedInstanceState);
 */